package com.abe.libfitness.utils;

import com.abe.libcore.utils.CommonUtils;
import com.abe.libfitness.entity.DataEntity;
import com.google.gson.Gson;

public class ProtocolV2Utils {
    private static final byte EMPTY = 0x00;
    private static final byte ADDRESS = (byte) 0xaa;//地址
    //协议码
    private static final byte TYPE_MOTOR = 0x11;//电机控制（启动、停止）
    private static final byte TYPE_POWER = 0x12;//力量设置
    private static final byte TYPE_DATA = 0x21;//数据接收

    //电机启动或者停止
    private static byte[] motorAction(boolean start) {
        byte action;
        if (start) {
            action = 0x01;
        } else {
            action = 0x00;
        }
        byte[] command = CRCChecker.getSendBuf(new byte[]{ADDRESS, TYPE_MOTOR, action, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY});
        CommonUtils.INSTANCE.log("*************" + new Gson().toJson(command));
        return command;
    }

    //number :0-150
    private static byte[] writePower(int number) {
        if (number > 150) number = 150;
        if (number < 0) number = 0;
        byte[] command = CRCChecker.getSendBuf(new byte[]{ADDRESS, TYPE_POWER, EMPTY, intToByte(number),
                EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY});
        CommonUtils.INSTANCE.log("*************" + new Gson().toJson(command));
        return command;
    }

    private static DataEntity parse(byte[] buffer) {
        DataEntity dataEntity = new DataEntity();
        dataEntity.setMotorStatus(byte2Int(buffer[2]));
        int distance = ProtocolV2Utils.byte2Int(buffer[3]) * 256 +
                ProtocolV2Utils.byte2Int(buffer[4]);
        dataEntity.setDistance(distance);
        int power = ProtocolV2Utils.byte2Int(buffer[5]) * 256 +
                ProtocolV2Utils.byte2Int(buffer[6]);
        dataEntity.setPower(power);
        return dataEntity;
    }

    //byte 与 int 的相互转换
    private static byte intToByte(int x) {
        return (byte) x;
    }

    private static int byte2Int(byte b) {
        return (int) (b & 0xff);
    }
}